package com.powernode.settings.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import com.github.pagehelper.PageInterceptor;
import com.powernode.commons.utils.ResponseData;
import com.powernode.settings.bean.UserBean;
import com.powernode.settings.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserService service;


    @GetMapping
    @ApiOperation("查询所有用户信息")
    public ResponseData getAll(){
        return service.findAll();
    }

    @GetMapping("code")
    @ApiOperation("获取验证码")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(80, 60, 4);
        //将真实的验证码存在session
        String code=gifCaptcha.getCode();
        // System.out.println(code);
        session.setAttribute("code", code);
        gifCaptcha.write(response.getOutputStream());
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public ResponseData login(String act,String psw,String code,HttpSession session){
        return service.login(act,psw,code,session);
    }

    @PostMapping("editPsw")
    @ApiOperation("修改密码")
    public ResponseData editPassword(String id,String oldPassword,String newPassword){
        return service.modifyPswById(id,oldPassword,newPassword);
    }

    @GetMapping("page")
    @ApiOperation("分页显示用户")
    public  ResponseData page(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false,defaultValue = "5") Integer pageSize){
        return service.page(pageNum,pageSize);
    }


    @PutMapping("editLockStateById")
    @ApiOperation("根据主键修改锁定状态")
    public ResponseData editLockStateById(String id,String state){
        return service.modifyLockStateById(id,state);
    }

    @PostMapping
    @ApiOperation("添加用户")
    public ResponseData add(@RequestBody UserBean user){
        return service.add(user);
    }

    @PutMapping
    @ApiOperation("修改用户")
    public ResponseData edit(@RequestBody UserBean user){
        return service.modify(user);
    }
}
